package m.common.model.config;

import m.common.model.*;
import m.system.listener.InitListener;
import m.system.util.AnnotationUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ModelConfig {
	private static boolean init=false;
	private static void doInit(){
		if(init) return;
		init=true;
		try {
			InitListener.initDB(null);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private static String tableSchema;
	private static List<Class<? extends Model>> tableList;
	private static Map<Class<? extends Model>,TableMeta> tableMap;
	private static Map<Class<? extends Model>,Map<String,FieldMeta>> fieldMetaMap;
	private static Map<Class<? extends Model>,Map<String,LinkTableMeta>> linkTableMetaMap;
	private static Map<Class<? extends Model>,Map<String, QueryFieldMeta>> queryFieldMetaMap;
	//set
	public static void setTableSchema(String tableSchema) {
		ModelConfig.tableSchema = tableSchema;
	}
	public static <T extends Model> void fillModelInfo(Class<T> clazz,TableMeta tableMeta,
			Map<String,FieldMeta> fieldMap,Map<String,LinkTableMeta> linkTableMap,Map<String,QueryFieldMeta> queryFieldMap){
		if(null==tableMap){
			tableList= new ArrayList<>();
			tableMap= new HashMap<>();
			fieldMetaMap= new HashMap<>();
			linkTableMetaMap= new HashMap<>();
			queryFieldMetaMap= new HashMap<>();
		}
		tableList.add(clazz);
		tableMap.put(clazz, tableMeta);
		fieldMetaMap.put(clazz, fieldMap);
		linkTableMetaMap.put(clazz, linkTableMap);
		queryFieldMetaMap.put(clazz, queryFieldMap);
		init=true;
	}
	//get
	public static <T extends Model> TableMeta getTableMeta(Class<T> clazz){
		doInit();
		if(null!=tableMap)
			return tableMap.get(clazz);
		else
			return null;
	}
	public static <T extends Model> Map<String,FieldMeta> getFieldMetaMap(Class<T> clazz){
		doInit();
		if(null!=fieldMetaMap){
			Map<String,FieldMeta> tmp=fieldMetaMap.get(clazz);
			if(null!=tmp) return tmp;
			tmp=AnnotationUtil.getAnnotationMap4Field(FieldMeta.class, clazz);
			return tmp;
		}
		return new HashMap<>();
	}
	public static <T extends Model> Map<String,LinkTableMeta> getLinkTableMetaMap(Class<T> clazz){
		doInit();
		if(null!=linkTableMetaMap){
			Map<String,LinkTableMeta> tmp=linkTableMetaMap.get(clazz);
			if(null!=tmp) return tmp;
			tmp=AnnotationUtil.getAnnotationMap4Field(LinkTableMeta.class, clazz);
			return tmp;
		}
		return new HashMap<>();
	}
	public static <T extends Model> Map<String, QueryFieldMeta> getQueryFieldMetaMap(Class<T> clazz){
		doInit();
		if(null!=queryFieldMetaMap){
			Map<String,QueryFieldMeta> tmp=queryFieldMetaMap.get(clazz);
			if(null!=tmp) return tmp;
			tmp=AnnotationUtil.getAnnotationMap4Field(QueryFieldMeta.class, clazz);
			return tmp;
		}
		return new HashMap<>();
	}
 	public static String getTableSchema() {
		return tableSchema;
	}
	public static List<Class<? extends Model>> getTableList() {
		doInit();
		return tableList;
	}
}
